#!/usr/bin/python3

# Copyright 2018-2019 Daniel 'grindhold' Brendle
#
# This file is part of libphexfile.
#
# libphexfile is free software: you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation, either
# version 3 of the License, or (at your option) any later
# version.
#
# libphexfile is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with libphexfile.
# If not, see http://www.gnu.org/licenses/.

import json
import sys

def create_axis_iterator(axis, f):
    def _iterator(parent_coords=[]):
        for x in range(axis["from"], axis["steps"]):
            coords = parent_coords +  [x]
            f(coords)
    return _iterator

def run():
    if len(sys.argv) != 2:
        print ("Expecting a json phexfile as first argument")

    data = json.loads(open(sys.argv[1]).read())

    template = data["energies"][0]

    for i in range(len(template[ len(data["coordinates"]) ])):
        for j in range(len(template[ len(data["coordinates"]) ][0])):
            template[len(data["coordinates"])][i][j] = None

    pos = []

    def add_pos(coord):
        pos.append(coord)

    axes = data["coordinates"]
    axes.reverse()
    iterator = add_pos
    for axis in axes:
        iterator = create_axis_iterator(axis, iterator)
    iterator()

    en = []
    off  = 0
    for i in range(0, len(pos)):
        try:
            e = data["energies"][i-off]
        except IndexError:
            e = [None] * len(data["coordinates"])
        correct_coord = True
        for x in range(0, len(data["coordinates"])):
            if pos[i][x] != e[x]:
                correct_coord = False
                break
        if not correct_coord:
            sys.stderr.write("Had to correct: "+repr(pos[i])+"\n")
            t = template.copy()
            for x in range(0, len(data["coordinates"])):
                t[x] = pos[i][x]
            en.append(t)
            off+=1
        else:
            en.append(e)
        
    data["energies"] = en
    print (json.dumps(data, indent=4))

if __name__ == "__main__":
    run()
